﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using MusicWorks.Web.Logic.Views;
using MusicWorks.Web.Logic.Views.Models;
using WebFormsMvp;
using MusicWorks.Web.Logic.CatalogService;
using MusicWorks.Web.Logic.Helpers;
using MusicWorks.Web.Logic.ShoppingService.svc;

namespace MusicWorks.Web.Logic.Presenters
{
    public class CategoryProductListPresenter : Presenter<ICategoryProductListView>
    {
        ICatalogService _catalogService;

        public CategoryProductListPresenter(ICategoryProductListView view)
            : this(view, ServiceBroker.CreateCatalogServiceInstance())
        {
        }

        public CategoryProductListPresenter(ICategoryProductListView view, ICatalogService catalogService)
            : base(view)
        {
            _catalogService = catalogService;

            View.Load += View_Load;
        }

        void View_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(View.CategoryId) || string.IsNullOrEmpty(View.CatalogName)) return;

            var products = _catalogService.GetProductsByCategory(View.CatalogName, View.CategoryId);
            View.Model.Products = products.Select(product => new ProductModel()
                                                           {
                                                               Id = product.Id,
                                                               DisplayName = product.DisplayName,
                                                               Description = product.Description,
                                                               FormattedPrice = string.Format("{0:C}", product.ListPrice),
                                                               Url = string.Concat("~/Product.aspx?id=", product.Id)
                                                           }).ToList();
        }

        public override void ReleaseView()
        {
            View.Load -= View_Load;
        }
    }
}
